<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>资源管理</el-breadcrumb-item>
      <el-breadcrumb-item>课程列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <div class="list">
        <el-row :gutter="20">
          <el-col :span="2">
            <el-button size="min" type="primary" @click="openAddDialog">新增</el-button>
          </el-col>

          <el-col :span="2">
            <div class="content">
              <el-date-picker
                :picker-options="searchStartTime"
                v-model="searchParams.startTime"
                clearable
                type="datetime"
                placeholder="上课时间"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
              ></el-date-picker>
            </div>
          </el-col>

          <el-col :span="2" :offset="4">
            <el-date-picker
              :picker-options="searchEndTime"
              v-model="searchParams.endTime"
              clearable
              type="datetime"
              placeholder="下课时间"
              format="yyyy-MM-dd HH:mm"
              value-format="yyyy-MM-dd HH:mm"
            ></el-date-picker>
          </el-col>

          <el-col :span="6" :offset="4">
            <el-tooltip content="搜索" placement="top" effect="dark">
              <el-button
                clearable
                type="success"
                icon="el-icon-search"
                plain
                circle
                @click="getCourseList"
              ></el-button>
            </el-tooltip>

            <el-tooltip content="导出到excel" placement="top" effect="dark">
              <el-button @click="exportExcel" round type="primary">
                导出
                <i class="el-icon-upload el-icon--right"></i>
              </el-button>
            </el-tooltip>
          </el-col>

          <el-col :span="4">
            <el-tooltip content="点击刷新" placement="top" effect="dark">
              <el-button
                @click="refreshTable"
                class="refresh"
                type="success"
                icon="el-icon-refresh"
                circle
              ></el-button>
            </el-tooltip>
          </el-col>
        </el-row>

        <el-table
          highlight-current-row
          :data="courseList"
          stripe
          border
          style="width: 1300px"
          header-align="center"
        >
          >
          <el-table-column align="center" prop="courseId" width="180" label="课程编号"></el-table-column>
          <el-table-column resizable prop="courseName" align="center" label="课程名称" width="190px">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>课程名: {{ scope.row.courseId }}</p>
                <p>教室名: {{ scope.row.classroomName }}</p>
                <p>任课老师: {{ scope.row.teacherName }}</p>
                <p>上课时间: {{ scope.row.beginTime }}</p>
                <p>下课时间: {{ scope.row.endTime }}</p>
                <p>时长: {{ scope.row.duration }}分钟</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag effect="plain" type="warning">
                    <span>{{ scope.row.courseName }}</span>
                  </el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column prop="classroomName" align="center" label="教室名称" width="80px">
            <template slot-scope="scope">
              <el-tag effect="dark">{{scope.row.classroomName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column sortable align="center" prop="className" width="180" label="授课班级"></el-table-column>

          <el-table-column prop="teacherName" align="center" label="任课老师" width="100px"></el-table-column>

          <el-table-column align="center" prop="beginTime" sortable label="上课时间" width="180px">
            <template slot-scope="scope">
              <el-tag type="success">
                <span style="margin-left: 10px">{{ scope.row.beginTime }}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="endTime" sortable label="下课时间" width="180px">
            <template slot-scope="scope">
              <el-tag type="danger">
                <span style="margin-left: 10px">{{ scope.row.endTime }}</span>
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column align="left" prop="duration" sortable label="时长" width="110px">
            <template slot-scope="scope">
              <i class="el-icon-alarm-clock"></i>
              <el-tag type="warning">{{scope.row.duration}}分钟</el-tag>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="140px">
            <template slot-scope="scope">
              <el-button
                class="edit"
                size="mini"
                type="success"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>
              <el-popconfirm
                @confirm="isconfirmDelete( scope.row)"
                confirm-button-text="我意已决"
                cancel-button-text="点错了"
                icon="el-icon-info"
                icon-color="red"
                title="确定要删除吗"
              >
                <el-button slot="reference" size="mini" type="danger">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchParams.currentPage"
          :page-sizes="[5, 10, 40, 80]"
          :page-size="searchParams.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>

      <!-- 课程修改对话框 -->
      <div class="dialog-form">
        <el-dialog
          modal
          top="60px"
          width="32%"
          @close="closeDialog"
          title="课程修改"
          :visible="updateCourseDialog"
          :before-close="handleClose"
        >
          <el-form
            label-position="right"
            :rules="rules"
            ref="modifyCourseRef"
            :model="courseForm"
            label-width="80px"
            class="courseForm"
          >
            <el-form-item label="教室名">
              <el-tag type="primary" effect="dark" v-text="courseForm.classroomName"></el-tag>
            </el-form-item>
            <el-form-item label="授课班级">
              <el-tag type="primary" effect="dark" v-text="courseForm.className"></el-tag>
            </el-form-item>
            <el-form-item prop="courseName" label="课程名称">
              <el-input
                clearable
                v-model="courseForm.courseName"
                class="form-input"
                autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item prop="teacherName" label="任课老师">
              <el-input
                clearable
                v-model="courseForm.teacherName"
                class="form-input"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="medium" type="primary" @click="modifyCourse('modifyCourseRef')">确 定</el-button>
            <el-button size="medium" @click="updateCourseDialog = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>

      <!-- 课程添加对话框 -->
      <div class="dialog-form">
        <el-dialog
          modal
          top="10px"
          width="35%"
          @close="closeDialog"
          title="课程添加"
          :visible="addCourseDialog"
          :before-close="handleClose"
        >
          <el-form
            label-position="left"
            :rules="rules"
            ref="addCourseRef"
            :model="courseForm"
            label-width="80px"
            class="courseForm"
          >
            <el-form-item prop="classroomId" label="教室名">
              <el-select
                @change="changeClassroom('addCourseRef')"
                filterable
                v-model="courseForm.classroomId"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in options"
                  :key="item.classroomId"
                  :label="item.classroomName"
                  :value="item.classroomId"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="classId" label="授课班级">
              <el-select
                @focus="getClassList()"
                filterable
                v-model="courseForm.classId"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in classOptions"
                  :key="item.classId"
                  :label="item.className"
                  :value="item.classId"
                ></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="beginTime" label="上课时间">
              <el-date-picker
                :picker-options="pickerOptionsStart"
                @change="changeClassroom('addCourseRef')"
                v-model="courseForm.beginTime"
                clearable
                type="datetime"
                placeholder="请选择"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
              ></el-date-picker>
            </el-form-item>

            <el-form-item prop="endTime" label="下课时间">
              <el-date-picker
                :picker-options="pickerOptionsEnd"
                @change="changeClassroom('addCourseRef')"
                v-model="courseForm.endTime"
                clearable
                type="datetime"
                placeholder="请选择"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
              ></el-date-picker>
            </el-form-item>
            <el-form-item prop="courseName" label="课程名称">
              <el-input
                clearable
                v-model="courseForm.courseName"
                class="form-input"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item prop="teacherName" label="任课老师">
              <el-input
                clearable
                v-model="courseForm.teacherName"
                class="form-input"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button size="medium" type="primary" @click="addCourse('addCourseRef')">确 定</el-button>
            <el-button size="medium" @click="addCourseDialog = false">取 消</el-button>
          </div>
        </el-dialog>
      </div>
    </el-card>
    <!-- 用户修改对话框 -->
  </div>
</template>

<script>
let moment = require("moment");

export default {
  inject: ["reload"],
  name: "ManagerList",
  data() {
    return {
      courseList: [], //总记录数
      searchParams: {
        currentPage: 1, //当前页
        limit: 5 //每页显示多少条,
      },
      total: 100, //总条数
      courseForm: {
        beginTime: "",
        endTime: ""
      },
      options: [],
      updateCourseDialog: false,
      addCourseDialog: false,
      rules: {
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" }
        ],
        classroomId: [{ required: true, message: "请选择", trigger: "blur" }],
        teacherName: [
          { required: true, message: "请输入任课老师", trigger: "blur" }
        ],
        classId: [{ required: true, message: "班级不能为空", trigger: "blur" }],
        beginTime: [
          { required: true, message: "上课时间时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "下课时间不能为空", trigger: "blur" }
        ]
      },
      pickerOptionsStart: {
        disabledDate: time => {
          if (this.courseForm.endTime != "") {
            return time.getTime() > new Date(this.courseForm.endTime).getTime();
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          return (
            time.getTime() <
            new Date(this.courseForm.beginTime).getTime() -
              1 * 24 * 60 * 60 * 1000
          );
        }
      },
      searchStartTime: {
        disabledDate: time => {
          if (this.searchParams.endTime != "") {
            return (
              time.getTime() > new Date(this.searchParams.endTime).getTime()
            );
          }
        }
      },
      searchEndTime: {
        disabledDate: time => {
          return (
            time.getTime() <
            new Date(this.searchParams.startTime).getTime() -
              1 * 24 * 60 * 60 * 1000
          );
        }
      },
      classOptions: [],
      selectOldClass: ""
    };
  },
  methods: {
    getClassList() {
      this.$http
        .get("/class/noAuthorize/all/class")
        .then(resp => {
          let { code, data, msg } = resp.data;
          if (code == 1) {
            console.log(data.classesList);
            this.classOptions = data.classesList;
          } else if (code == 503) {
            this.$message.warning(msg);
          }
        })
        .catch(resp => {});
    },
    exportExcel() {
      require.ensure([], () => {
        const { export_json_to_excel } = require("@/excel/Export2Excel");
        const tHeader = [
          "课程编号",
          "课程名字",
          "教室名",
          "授课班级",
          "开始时间",
          "结束时间",
          "时长",
          "授课讲师"
        ];
        const filterVal = [
          "courseId",
          "courseName",
          "classroomName",
          "className",
          "beginTime",
          "endTime",
          "duration",
          "teacherName"
        ];

        const list = JSON.parse(JSON.stringify(this.courseList));
        list.forEach(el => {
          el.duration = el.duration + "分钟";
        });
        const data = this.formatJson(filterVal, list);
        export_json_to_excel(tHeader, data, "课程安排");
      });
    },
    // 参数过滤
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]));
    },
    changeClassroom(addCourseRef) {
      let validateList = [];
      this.$refs["addCourseRef"].validateField(
        ["classroomId", "beginTime", "endTime"],
        message => {
          validateList.push(message);
        }
      );

      if (validateList.every(item => item === "")) {
        // 咱们的操作
        this.$http
          .get("/course/noAuthorize/checkCourseIsAvailable", {
            params: {
              classroomId: this.courseForm.classroomId,
              beginTime: this.courseForm.beginTime,
              endTime: this.courseForm.endTime
            }
          })
          .then(resp => {
            let { code } = resp.data;
            if (code === 1) {
              this.$message.success("时间选择无冲突");
            }
          })
          .catch(resp => {});
      }
    },
    addCourse(addCourseRef) {
      this.$refs[addCourseRef].validate(valid => {
        if (valid) {
          this.$http
            .post("/course/addCourse", this.courseForm)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code === 1) {
                this.$message.success(msg);
              } else {
                this.$message.error(msg);
              }
              this.addCourseDialog = false;
            })
            .catch(resp => {});
        } else {
          this.$message.info("请先填完内容");
        }
      });
    },
    openAddDialog() {
      this.courseForm = {};
      this.getClassroomSelectList();
      this.addCourseDialog = true;
    },

    getCourseList() {
      this.$http
        .get("/course/noAuthorize/getCourseListByCondition", {
          params: {
            startTime: this.searchParams.startTime,
            endTime: this.searchParams.endTime
          }
        })
        .then(resp => {
          let { code } = resp.data;
          let { courseVoList, total, currentPage, pageSize } = resp.data.data;
          if (code === 1) {
            this.courseList = courseVoList;
            this.total = parseInt(total);
          } else {
            this.$message.info("数据没有找到");
          }
        })
        .catch(resp => {});
    },
    getClassroomSelectList() {
      this.$http
        .get("/classroom/noAuthorize/getClassroomOptions")
        .then(resp => {
          let { code, msg } = resp.data;
          let { options } = resp.data.data;
          if (code === 1) {
            return (this.options = options);
          }
          return this.$message.info(msg);
        })
        .catch(resp => {});
    },
    modifyCourse(courseFormRef) {
      this.$refs[courseFormRef].validate(valid => {
        if (valid) {
          // 发送axios请求
          let params = new URLSearchParams();
          params.append("courseId", this.courseForm.courseId);
          params.append("teacherName", this.courseForm.teacherName);
          params.append("courseName", this.courseForm.courseName);
          this.$http
            .put("/course/updateCourse/", params)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code === 1) {
                this.$message({
                  showClose: true,
                  message: msg,
                  type: "success"
                });
              } else {
                this.$message({
                  showClose: true,
                  message: msg,
                  type: "warning"
                });
              }
            })
            .catch(resp => {});
          this.getCourseList();
          this.updateCourseDialog = false;
        } else {
          this.$message.info("请先填完内容");
        }
      });
    },

    handleEdit(index, row) {
      this.courseForm = row;
      this.updateCourseDialog = true;
    },
    isconfirmDelete(row) {
      this.$http
        .delete("/course/deleteCourse/" + row.courseId)
        .then(resp => {
          let code = resp.data.code;
          if (code === 1) {
            this.$message({
              showClose: true,
              message: "删除成功！",
              type: "success"
            });
          } else {
            this.$message({
              showClose: true,
              message: resp.data.msg,
              type: "warning"
            });
          }
          this.getCourseList();
        })
        .catch(resp => {});
    },

    handleSizeChange(limit) {
      this.$http
        .get("/course/noAuthorize/getCourseListByCondition", {
          params: {
            startTime: this.searchParams.startTime,
            endTime: this.searchParams.endTime,
            page: this.searchParams.page,
            limit: limit
          }
        })
        .then(resp => {
          let { code } = resp.data;
          let { courseVoList, total, currentPage, pageSize } = resp.data.data;
          if (code === 1) {
            this.courseList = courseVoList;
            this.total = parseInt(total);
          } else if (code == 404) {
            this.$message.info("数据为空");
          } else {
            this.$message.error(msg);
          }
        })
        .catch(resp => {});
    },
    handleCurrentChange(page) {
      this.$http
        .get("/course/noAuthorize/getCourseListByCondition", {
          params: {
            startTime: this.searchParams.startTime,
            endTime: this.searchParams.endTime,
            page: page,
            limit: this.searchParams.limit
          }
        })
        .then(resp => {
          let { code } = resp.data;
          let { courseVoList, total, currentPage, pageSize } = resp.data.data;
          if (code === 1) {
            this.courseList = courseVoList;
            this.total = parseInt(total);
          } else if (code == 404) {
            this.$message.info("数据为空");
          } else {
            this.$message.error(msg);
          }
        })
        .catch(resp => {});
    },
    refreshTable() {
      this.reload();
      this.$message.success("已刷新");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(resp => {
          this.getCourseList();
          this.updateCourseDialog = false;
          this.addCourseDialog = false;
          done();
        })
        .catch(resp => {
          this.getCourseList();
        });
    },
    closeDialog() {
      this.getCourseList();
    }
  },
  created() {
    this.getCourseList();
  }
};
</script>

<style scoped>
.el-input {
  width: 150px;
  margin-right: 10px;
}
.el-row {
  margin-bottom: 10px;
}
.refresh {
  float: right;
  margin-right: 20px;
}

.list {
  margin-top: 25px;
  margin-left: 20px;
}
.form-input {
  width: 200px;
}
.el-form {
  margin-left: 30px;
}
.el-card {
  margin-top: 20px;
}

.batchdelete {
  margin-left: 38px;
}

.edit {
  float: left;
}
.el-input,
.el-textarea {
  width: 217px;
}
.searchParamInput {
  width: 170px;
}
.list {
  margin-top: 10px;
}
.el-breadcrumb {
  margin-top: 10px;
}
</style>